<template>
    <div class="post-manage-page">

        <!-- 主内容区域 -->
        <div class="main-content">

            <!-- 右侧内容区域 -->
            <main class="manage-main">
                <div class="manage-container">
                    <!-- 页面标题 -->
                    <div class="page-header">
                        <h1 class="page-title">动态管理</h1>
                    </div>

                    <!-- 搜索和筛选区域 -->
                    <div class="filter-section">
                        <div class="search-group">
                            <el-select v-model="searchType" placeholder="搜索类型" style="width: 120px">
                                <el-option label="动态内容" value="content" />
                                <el-option label="发布者昵称" value="author" />
                            </el-select>
                            <el-input v-model="searchKeyword" placeholder="搜索动态..." class="search-input"
                                @keyup.enter="handleSearch" clearable @clear="handleClearSearch">
                                <template #prefix>
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                搜索
                            </el-button>
                        </div>
                    </div>

                    <!-- 动态列表表格 -->
                    <div class="table-section">
                        <el-table :data="posts" v-loading="loading" style="width: 100%">
                            <el-table-column prop="post_id" label="ID" width="80" />
                            <el-table-column label="内容" min-width="200">
                                <template #default="{ row }">
                                    <div class="post-content-cell">
                                        <div class="content-text" :title="row.content">
                                            {{ row.content }}
                                        </div>
                                        <div v-if="getPostImages(row).length > 0" class="content-images">
                                            <el-tag size="small" type="info">
                                                {{ getPostImages(row).length }}张图片
                                            </el-tag>
                                            <el-button type="text" size="small" @click="previewPostImages(row)">
                                                预览
                                            </el-button>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="like_count" label="点赞数" width="80" align="center" />
                            <el-table-column prop="comment_count" label="评论数" width="80" align="center">
                                <template #default="{ row }">
                                    <el-button type="primary" link @click="showPostComments(row.post_id)">
                                        {{ row.comment_count }}
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="发布者" min-width="150">
                                <template #default="{ row }">
                                    <div class="author-info">
                                        <div class="author-name">{{ row.author?.nickname || '未知用户' }}</div>
                                        <div class="author-id">ID: {{ row.user_id }}</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="联系方式" min-width="180">
                                <template #default="{ row }">
                                    <div class="contact-info">
                                        <div v-if="row.author?.phone" class="phone">
                                            {{ row.author.phone }}
                                        </div>
                                        <div v-else class="no-phone">未填写</div>
                                        <div v-if="row.author?.email" class="email" :title="row.author.email">
                                            {{ row.author.email }}
                                        </div>
                                        <div v-else class="no-email">未填写</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="发布时间" width="180">
                                <template #default="{ row }">
                                    {{ formatTime(row.created_at) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="info" size="small" @click="showPostComments(row.post_id)">
                                        评论
                                    </el-button>
                                    <el-button type="danger" size="small" @click="handleDeletePost(row.post_id)"
                                        :loading="row.deleting">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页组件 -->
                    <div v-if="posts.length > 0" class="pagination-section">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </main>
        </div>

        <!-- 动态图片预览模态框 -->
        <el-dialog v-model="imagePreviewVisible" title="动态图片" width="80%" top="5vh" align-center>
            <div class="image-preview-section">
                <div class="preview-header">
                    <h3>动态ID: {{ currentPost?.post_id }}</h3>
                    <div class="image-count">共 {{ previewImages.length }} 张图片</div>
                </div>
                <div class="images-grid">
                    <div v-for="(image, index) in previewImages" :key="index" class="image-item">
                        <img :src="image" :alt="`图片${index + 1}`" @click="previewSingleImage(index)"
                            class="preview-img" />
                        <div class="image-index">图片 {{ index + 1 }}</div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 单张图片预览模态框 -->
        <el-dialog v-model="singleImagePreviewVisible" title="图片预览" width="60%" top="5vh" align-center>
            <div class="single-image-preview">
                <img :src="currentPreviewImage" alt="预览图片" class="single-preview-image" />
                <div class="preview-navigation">
                    <el-button @click="prevImage" :disabled="currentImageIndex === 0">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        上一张
                    </el-button>
                    <span class="image-counter">{{ currentImageIndex + 1 }} / {{ previewImages.length }}</span>
                    <el-button @click="nextImage" :disabled="currentImageIndex === previewImages.length - 1">
                        下一张
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 评论管理模态框 -->
        <el-dialog v-model="commentsDialogVisible" title="评论管理" width="900px" :before-close="handleCloseCommentsDialog">
            <div class="comments-section">
                <div class="comments-header">
                    <h3>动态ID: {{ currentPostId }} - 评论列表</h3>
                    <span class="comment-count">共 {{ postComments.length }} 条评论</span>
                </div>

                <div class="comments-list">
                    <div v-for="comment in postComments" :key="comment.comment_id" class="comment-item">
                        <div class="comment-header">
                            <div class="commenter-info">
                                <span class="commenter-name">{{ comment.commenter?.nickname || '匿名用户' }}</span>
                                <span class="commenter-id">(ID: {{ comment.user_id }})</span>
                            </div>
                            <div class="comment-time">{{ formatTime(comment.created_at) }}</div>
                        </div>
                        <div class="comment-content">{{ comment.content }}</div>
                        <div class="comment-actions">
                            <el-button type="danger" size="small" @click="handleDeleteComment(comment.comment_id)"
                                :loading="comment.deleting">
                                删除评论
                            </el-button>
                        </div>
                    </div>

                    <div v-if="postComments.length === 0" class="no-comments">
                        <el-empty description="暂无评论" />
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { usePostsStore } from '@/stores/posts'

const router = useRouter()
const postsStore = usePostsStore()

// 响应式数据
const searchKeyword = ref('')
const searchType = ref('content')
const loading = ref(false)
const isSearching = ref(false)
const activeSidebar = ref('admin')

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 动态列表
const posts = ref([])

// 图片预览相关
const imagePreviewVisible = ref(false)
const singleImagePreviewVisible = ref(false)
const currentPost = ref(null)
const previewImages = ref([])
const currentImageIndex = ref(0)
const currentPreviewImage = computed(() => previewImages.value[currentImageIndex.value] || '')

// 评论管理相关
const commentsDialogVisible = ref(false)
const currentPostId = ref(null)
const postComments = ref([])
const commentsLoading = ref(false)

// 初始化加载
onMounted(() => {
    fetchPosts()
})

// 监听分页变化
watch([currentPage, pageSize], () => {
    if (!isSearching.value) {
        fetchPosts()
    } else {
        handleSearch()
    }
})

// 获取动态列表
const fetchPosts = async () => {
    try {
        loading.value = true
        const response = await postsStore.fetchPosts({
            page: currentPage.value,
            pageSize: pageSize.value,
            include_author: true // 包含作者信息
        })
        if (response.code === 0) {
            posts.value = response.data.list || []
            total.value = response.data.pagination?.total || posts.value.length
        }
    } catch (error) {
        ElMessage.error('获取动态列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 获取帖子图片
const getPostImages = (post) => {
    if (!post.images || post.images === 'null' || post.images === null) {
        return []
    }

    try {
        if (Array.isArray(post.images)) {
            return post.images.filter(img => img && img.trim())
        }

        if (typeof post.images === 'string') {
            const images = post.images.split(',').filter(img => img && img.trim())
            return images.map(img => img.trim())
        }

        return []
    } catch (error) {
        console.error('图片数据解析错误:', error)
        return []
    }
}

// 搜索动态
const handleSearch = async () => {
    if (!searchKeyword.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
    }

    try {
        loading.value = true
        isSearching.value = true
        currentPage.value = 1

        const response = await postsStore.fetchPosts({
            search_keyword: searchKeyword.value.trim(),
            search_type: searchType.value,
            page: currentPage.value,
            pageSize: pageSize.value,
            include_author: true
        })
        if (response.code === 0) {
            posts.value = response.data.list || []
            total.value = response.data.pagination?.total || posts.value.length

            const searchTypeText = searchType.value === 'content' ? '动态内容' : '发布者昵称'
            ElMessage.success(`在${searchTypeText}中找到 ${total.value} 条相关动态`)
        }
    } catch (error) {
        ElMessage.error('搜索失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 清空搜索
const handleClearSearch = () => {
    searchKeyword.value = ''
    searchType.value = 'content'
    isSearching.value = false
    currentPage.value = 1
    fetchPosts()
}

// 每页条数变化
const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}

// 删除动态
const handleDeletePost = async (postId) => {
    try {
        await ElMessageBox.confirm('确定要删除这条动态吗？此操作将同时删除所有相关评论，且不可恢复。', '确认删除', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        const post = posts.value.find(p => p.post_id === postId)
        if (post) {
            post.deleting = true
        }

        const response = await postsStore.removePost(postId)
        if (response.code === 0) {
            ElMessage.success('删除动态成功')
            fetchPosts()
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除')
        } else {
            ElMessage.error('删除动态失败：' + error.message)
        }
    } finally {
        const post = posts.value.find(p => p.post_id === postId)
        if (post) {
            post.deleting = false
        }
    }
}

// 预览动态图片
const previewPostImages = (post) => {
    currentPost.value = post
    previewImages.value = getPostImages(post)
    imagePreviewVisible.value = true
}

// 预览单张图片
const previewSingleImage = (index) => {
    currentImageIndex.value = index
    singleImagePreviewVisible.value = true
}

// 上一张图片
const prevImage = () => {
    if (currentImageIndex.value > 0) {
        currentImageIndex.value--
    }
}

// 下一张图片
const nextImage = () => {
    if (currentImageIndex.value < previewImages.value.length - 1) {
        currentImageIndex.value++
    }
}

// 显示动态评论
const showPostComments = async (postId) => {
    try {
        commentsLoading.value = true
        currentPostId.value = postId
        const response = await postsStore.getPostCommentsAction(postId, {
            page: 1,
            pageSize: 100 // 加载所有评论
        })
        if (response.code === 0) {
            postComments.value = response.data.list || response.data || []
            commentsDialogVisible.value = true
        }
    } catch (error) {
        ElMessage.error('获取评论失败：' + error.message)
    } finally {
        commentsLoading.value = false
    }
}

// 删除评论
const handleDeleteComment = async (commentId) => {
    try {
        await ElMessageBox.confirm('确定要删除这条评论吗？此操作不可恢复。', '确认删除', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        const comment = postComments.value.find(c => c.comment_id === commentId)
        if (comment) {
            comment.deleting = true
        }

        await postsStore.deleteCommentAction(commentId)
        ElMessage.success('删除评论成功')

        // 从列表中移除
        postComments.value = postComments.value.filter(c => c.comment_id !== commentId)

        // 更新动态的评论数
        const post = posts.value.find(p => p.post_id === currentPostId.value)
        if (post) {
            post.comment_count = Math.max(0, post.comment_count - 1)
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除')
        } else {
            ElMessage.error('删除评论失败：' + error.message)
        }
    } finally {
        const comment = postComments.value.find(c => c.comment_id === commentId)
        if (comment) {
            comment.deleting = false
        }
    }
}

// 关闭评论对话框
const handleCloseCommentsDialog = () => {
    commentsDialogVisible.value = false
    postComments.value = []
    currentPostId.value = null
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return ''
    return new Date(timeString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.post-manage-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
}

/* 主内容区域 */
.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.manage-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 20px;
}

.manage-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面标题 */
.page-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
}

.page-title {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

/* 筛选区域 */
.filter-section {
    margin-bottom: 20px;
}

.search-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-input {
    width: 300px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 24px;
}

/* 内容单元格样式 */
.post-content-cell {
    max-width: 300px;
}

.content-text {
    margin-bottom: 8px;
    line-height: 1.4;
    color: #333;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.content-images {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* 作者信息样式 */
.author-info {
    line-height: 1.4;
}

.author-name {
    font-weight: 500;
    color: #333;
}

.author-id {
    font-size: 12px;
    color: #999;
}

/* 联系信息样式 */
.contact-info {
    line-height: 1.4;
}

.phone,
.email {
    font-size: 13px;
    color: #333;
}

.email {
    max-width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.no-phone,
.no-email {
    font-size: 12px;
    color: #999;
    font-style: italic;
}

/* 分页 */
.pagination-section {
    display: flex;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
}

/* 图片预览样式 */
.image-preview-section {
    padding: 0 10px;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.preview-header h3 {
    margin: 0;
    color: #303133;
}

.image-count {
    color: #606266;
    font-size: 14px;
}

.images-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    max-height: 500px;
    overflow-y: auto;
}

.image-item {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 8px;
    text-align: center;
}

.preview-img {
    width: 100%;
    height: 150px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 0.2s;
}

.preview-img:hover {
    transform: scale(1.05);
}

.image-index {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
}

/* 单张图片预览 */
.single-image-preview {
    text-align: center;
}

.single-preview-image {
    max-width: 100%;
    max-height: 60vh;
    object-fit: contain;
    border-radius: 8px;
}

.preview-navigation {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;
    margin-top: 16px;
}

.image-counter {
    color: #666;
    font-size: 14px;
}

/* 评论管理样式 */
.comments-section {
    padding: 0 10px;
}

.comments-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.comments-header h3 {
    margin: 0;
    color: #303133;
}

.comment-count {
    color: #606266;
    font-size: 14px;
}

.comments-list {
    max-height: 500px;
    overflow-y: auto;
}

.comment-item {
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    margin-bottom: 12px;
    background: #f8f9fa;
}

.comment-item:last-child {
    margin-bottom: 0;
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.commenter-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.commenter-name {
    font-weight: 500;
    color: #333;
}

.commenter-id {
    font-size: 12px;
    color: #999;
}

.comment-time {
    font-size: 12px;
    color: #999;
}

.comment-content {
    margin-bottom: 12px;
    line-height: 1.5;
    color: #333;
    word-break: break-word;
}

.no-comments {
    padding: 40px 0;
    text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .manage-main {
        margin-left: 240px;
        padding: 16px;
    }

    .manage-container {
        padding: 16px;
    }

    .search-group {
        flex-direction: column;
        align-items: stretch;
    }

    .search-input {
        width: 100%;
    }

    .images-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }
}
</style>